/**
 * DES加密服务
 * QL_WEB_DES_KEY 约定好的key不要泄露
 * encryptedDES 加密
 * decryptedDES 解密
 */
import { Injectable } from '@angular/core';
import * as CryptoJS from 'crypto-js/crypto-js';
@Injectable({
    providedIn: 'root'
})
export class CrtptoService {
    public QL_WEB_DES_KEY: String = "qlweb123456789"
    public QL_WEB_DES_JAVA_KEY: String = "453e57e90167a1c4"

    constructor() { }

    /**
     * 
     * @param data 加密
     */
    public encryptedDES(data: any): string {
        const keyHex = CryptoJS.enc.Utf8.parse(this.QL_WEB_DES_KEY);
        //模式为ECB padding为Pkcs7
        const encrypted = CryptoJS.DES.encrypt(data, keyHex, {
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.Pkcs7
        });
        //加密出来是一个16进制的字符串
        return encrypted.ciphertext.toString();
    }
    /**
     * 
     * @param data 解密
     */
    public decryptedDES(data: any): string {
        const keyHex = CryptoJS.enc.Utf8.parse(this.QL_WEB_DES_KEY);
        const decrypted = CryptoJS.DES.decrypt({
            ciphertext: CryptoJS.enc.Hex.parse(data)
        }, keyHex, {
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.Pkcs7
        });
        //以utf-8的形式输出解密过后内容
        return decrypted.toString(CryptoJS.enc.Utf8);
    }
    /**
     * 
     * @param data 解密
     */
    public decryptedDESByKey(data: any, key: string): string {
        const keyHex = CryptoJS.enc.Utf8.parse(key);
        const decrypted = CryptoJS.DES.decrypt({
            ciphertext: CryptoJS.enc.Hex.parse(data)
        }, keyHex, {
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.Pkcs7
        });
        //以utf-8的形式输出解密过后内容
        return decrypted.toString(CryptoJS.enc.Utf8);
    }
    /**
     * 
     * @param str RSA公钥加密
     */
    public decryptDESJAVA(data: String) {
        const keyHex = CryptoJS.enc.Utf8.parse(this.QL_WEB_DES_JAVA_KEY);
        const decrypted = CryptoJS.DES.decrypt({
            ciphertext: CryptoJS.enc.Hex.parse(data)
        }, keyHex, {
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.Pkcs7
        });
        //以utf-8的形式输出解密过后内容
        return decrypted.toString(CryptoJS.enc.Utf8);
    }

}
